<?php 
namespace common\service;

use common\model\sell66\User;
use common\model\sell66\UserLoginLog;
use common\model\sell66\UserBank;
use common\model\sell66\UserSteam;
use common\libs\AES;
class UserService{
	
	public static $instance = null;
	
	private function __construct(){
	}
	public static function getInstance(){
		if(self::$instance == null){
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	
	public function getInviteCode($userId){
		$type = RaffleService::getInstance()->getCurrentType();
		$aes = new AES();
		return  $aes->encode($type.'|'.$userId);
	}
	
	public function plusRatio($userId,$appId){
		$ratioInfo['totalAdditon'] = 0;

		return $ratioInfo;
	}
	
	
	public function checkSetTradePwd($userId){
		$user = User::getUsersByUserId($userId);
		if(empty($user['transaction_pwd'])){
			return false;
		}
		return true;
	}

    public function checkWalletAddress($userId){
        $user = User::getUsersByUserId($userId);
        if(!empty($user['wallet_address'])){
            return ['wallet_address'=>$user['wallet_address']];
        }
        return false;
    }
	
	public function checkTradePwd($userId,$pwd){
		$user = User::getUsersByUserId($userId);
		return $user->checkTransPwd($pwd);
	}
	
	public function createUserBySteam($steamUserInfo,$user=[]){
		$userSteam = User::createUserBySteam($steamUserInfo,$user);
		$result = $userSteam;
		$userId = $userSteam['user_id'];
		$walletInfo = WalletService::getInstance()->info($userId);
		$result['balance'] = $walletInfo['balance'];
		$result['freezeBalance'] = $walletInfo['freezeBalance'];
		return $result;
	}

    public function updateUserBySteam($userId,$steamUserInfo){
        $userSteam = UserSteam::updateUserBySteam($userId,$steamUserInfo);
        $result = $userSteam;
        $userId = $userSteam['user_id'];
        $walletInfo = WalletService::getInstance()->info($userId);
        $result['balance'] = $walletInfo['balance'];
        $result['freezeBalance'] = $walletInfo['freezeBalance'];
        return $result;
    }
	
	public function getUserInfoBySteamId($steamId){
		$userSteam = UserSteam::findBySteamId($steamId);
		if(empty($userSteam)){
			return null;
		}
		$result = $userSteam->toArray();
		$userId = $userSteam['user_id'];
		$walletInfo = WalletService::getInstance()->info($userId);
		$result['balance'] = $walletInfo['balance'];
		$result['freezeBalance'] = $walletInfo['freezeBalance'];
		return $result;
	}

    public function getUserInfoByUserId($userId){
        $userSteam = UserSteam::getUserInfo($userId);
        if(empty($userSteam)){
            return null;
        }
        $result = $userSteam->toArray();
        $walletInfo = WalletService::getInstance()->info($userId);
        $result['balance'] = $walletInfo['balance'];
        $result['freezeBalance'] = $walletInfo['freezeBalance'];
        return $result;
    }
	
	public function  setTradeUrl($userId, $steamId, $tradeUrl,$trade_token){
		return UserSteam::setTradeUrl($userId, $steamId, $tradeUrl,$trade_token);
	}
	
	public function getWithdrawRecord($userId,$offset,$limit){
		$records = UserWithdrawRecord::getUserRecord($userId,$offset,$limit);
	}
	
	public function addFeedback($userId,$message,$email,$qq,$mobile){
        if(UserFeedback::addFeedback($userId,$message,$email,$qq,$mobile)){
            return true;
        }else{
            return false;
        }
	}

	public function refreshUserLoginTime($userId){
        User::refreshLoginTimeByUserId($userId);
    }
	
	public function saveUserBank($userId,$bankType,$account,$realName,$bankId = 0){
		$user_bank_id = 0;
		if($bankType == 2){//存入支付宝
			$bankName = "支付宝";
			$bankType = 'alipay';
			$user_bank_id = UserBank::saveUserBank($userId, $realName, $account, $bankType, $bankName,$bankId);
		}elseif($bankType == 3){
			$bankType = 'bankcard';
			$bank = Bank::getById($bankId);
			$bankName = $bank['bank_name'];
			$user_bank_id = UserBank::saveUserBank($userId, $realName, $account, $bankType, $bankName,$bankId);
		}
		return $user_bank_id;
	}

	private function saltTransPwd($length = 4){
		$salt = '';
		for ($i = 0; $i < $length; $i++){
			$salt .= chr(rand(33, 126));
		}
		return $salt;
	}
	
	public function saveUserTransactionPwd($userId, $transPwd, $email)
    {	
    	$salt = $this->saltTransPwd();
    	$transPwd = md5(md5($transPwd) . $salt);
        return User::saveTransPwd($userId, $transPwd, $salt, $email);
    }

    public function checkEmail($userId, $email)
    {
        $result = User::getUserInfoByUserId($userId);
        if(!empty($result['email'])){
            // 存在即修改,验证邮箱是否一致
            if($result['email'] != $email) return -1;
            return true;
        }else{
            // 不存在则验证邮箱唯一
            $existence = User::getUserByEmail($email);
            if($existence) return -2;
            return true;
        }
    }
    
    public function hasEmail($userId)
    {
    	$result = User::getUserInfoByUserId($userId);
    	if(!empty($result['email'])){
    		// 存在即修改,验证邮箱是否一致
    		return $result['email'];
    	}else{
    		return false;
    	}
    }

    // 交易状态 1成功 2失败
    public function userSendEmail($userId, $status = 2, $orderPrice = null, $cashType = null)
    {
        $result = User::getUserInfoByUserId($userId);
        if(empty($result['email'])){
            return false;
        }
        $email = [$result['email']];

        if($status == 1){
            $content = ['%orderPrice%'=>[$orderPrice], '%cashType%'=>[$cashType]];
            return MailService::getInstance()->setTemplate('order_success_template')->send($email, $content);
        }elseif($status){
            return MailService::getInstance()->setTemplate('error_template')->send($email);
        }
        return false;
    }

    // 检查用户是白名单
    public function checkUserWhite($userId)
    {
        $userInfo = User::getUsersByUserId($userId);
        $result = false;
        if($userInfo['isblack'] == 1){
            $result = true;
        }
        return $result;
    }

    /**
     * 创建用户登录日志
     * @param $userId
     */
    public function createUserLoginLog($userId){
        $userSteam = UserSteam::getUserInfo($userId);
        $addData['user_id'] = $userId;
        $addData['personaname'] = $userSteam['personaname'];
        $addData['login_ip'] = $this->getIp();
        return UserLoginLog::createUserLoginLog($addData);
    }

    /**
     * 获取客户端ip
     * @return array|false|string
     */
    public function getIp()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return $ip;
    }

    /**
	 * 分享解密
	 * @param  string $inviteToken token值
	 * @return string
	 */
	public function inviteDecode($inviteToken)
	{
		$object = new AES();
		$inviteToken = str_replace(" ", "+", $inviteToken);
		return $object->decode($inviteToken);
	}

	/**
	 * 添加邀请信息
	 * @param string $inviteCode 邀请码
	 * @param int $toUserId 被邀请用户ID
	 * @return string|bool
	 */
    public function addInviteLog($inviteCode, $toUserId)
    {
		if (empty($inviteCode)) {
			return false;
		}

		$checkInvite = UserService::getInstance()->checkUserInviteCode($inviteCode);
		if (!$checkInvite) {
			// 活动邀请码
			$code = $this->inviteDecode($inviteCode);
			if (empty($code)) {
				return false;
			}
			list($source, $fromUserId) = explode('|', $code);

			$userDetails = User::getUsersByUserId($fromUserId);
			if (!$userDetails) {
				// query user details failed
				return false;
			}
		} else {
			// 推广邀请码
			$fromUserId = $checkInvite['user_id'];
			$source = 'commission';
		}

		$count = InviteLog::getInviteLogNum($fromUserId, $toUserId, $source);
		if ($count > 0) {
			return false;
		}

		$res =  InviteLog::addInviteLog($fromUserId, $toUserId, $source);
		if (!$res) {
            // insert invite log failed
            return false;
		}
		return $source;
    }

	/**
	 * 检查是否是用户邀请码
	 * @param string $inviteCode 邀请码
	 * @return bool
	 */
    public function checkUserInviteCode($inviteCode)
    {
    	$users = User::checkUserInviteCode($inviteCode);
    	if (!$users) {
    		return false;
    	}
    	return $users;
    }

    // 直接用user_id进行登录
    public function userLogin($userId)
    {
        // 绑定则直接登录
        $userSteam = UserService::getInstance()->getUserInfoByUserId($userId);
        $userInfo = AuthService::getInstance()->saveSteamLoginInfo($userSteam);
        $token = $userInfo['access_token'];
        if(isset($userInfo['user_id']) && !empty($userInfo['user_id'])){
            $userId = $userInfo['user_id'];
            // 更新用户登录时间
            User::refreshLoginTimeByUserId($userId);
            UserService::getInstance()->createUserLoginLog($userSteam['user_id']);
        }
        return $token;
    }

    public function saveWalletAddress($userId, $walletAddress)
    {
        return User::saveWalletAddress($userId, $walletAddress);
    }
}